const express = require("express");
const router = express.Router();
const db = require('../db');

router.post("/login", (req, res) => {
  const { username, password } = req.body;
  db.serialize(() => {
    db.all(`SELECT * FROM user`, (err, rows) => {
      if (err) {
        console.error(err);
      } else {
        if (rows.length > 0) {
          const user = rows.find(row => row.username === username && row.password === password);
          if (user) {
            res.send("登录成功");
          } else {
            res.send("密码或用户名错误");
          }
        } else {
          res.send("用户不存在");
        }
      }
    });
  });
});

router.post("/register",(req,res)=>{
  const { username, password } = req.body;
  if(!username || !password){
    res.send("用户名或密码不能为空");
    return;
  }
  db.run(`INSERT INTO user (username, password) VALUES (?,?)`,[username,password],(err)=>{
    if(err){
      console.error(err);
      res.send("注册失败");
    }else{
      res.send("注册成功");
    }
  });
});

module.exports = router;
